//
//  QBOauthViewController.swift
//  Wei91BoiOS
//
//  Created by bing on 16/3/21.
//  Copyright © 2016年 bing. All rights reserved.
//

import UIKit

import SVProgressHUD

class QBOauthViewController: UIViewController {

    override func loadView() {
        
        // 在这里设置控制器的View为webView的好处是后面需要添加约束，自己会和屏幕一样大
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 添加webView
        //self.view.addSubview(webView)
        // 设置webView的约束
        
        // 没有背景颜色，在Modal的时候只看到导航栏
        view.backgroundColor = UIColor.whiteColor()
        
        setupNavigationBar()
        
        // 使用webView加载登陆界面
        let curlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        // 登录界面需要查看API文档
        let url = NSURL(string: curlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        // 弹出正在加载的提示
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.None)
        
        // showInfoWith,会自动关闭
        //SVProgressHUD.showInfoWithStatus("正在加载", maskType: SVProgressHUDMaskType.Clear)
        
        //SVProgressHUD.showErrorWithStatus("正在加载")
    }
    
    // 设置导航栏
    private func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    // MARK: - 点击的方法
    @objc private func autoFill() {
        //document.getElementById('userId').value='1715902601@qq.com’
        
        //document.getElementById('passwd').value='Yb13767096968'
        let jsCode = "document.getElementById('userId').value='1715902601@qq.com';document.getElementById('passwd').value='Yb13767096968'"
        
        // 执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    
    // 关闭控制器
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }

    // MARK: - 懒加载
    /// webView
    private lazy var webView: UIWebView = UIWebView()
}

// MARK: - 扩展QBOauthViewController 实现UIWebViewDelegate
extension QBOauthViewController: UIWebViewDelegate {
    
    func webViewDidFinishLoad(webView: UIWebView) {
        // 关闭提示
        SVProgressHUD.dismiss()
    }
    
    // webView是否需要加载某个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // true 表示加载这个地址，false就不去加载
        
        let urlString = request.URL!.absoluteString
       
        print("urlString:\(urlString)")
        // 点击取消："https://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330"
        
        // 点击授权："https://www.baidu.com/?code=510e071daf99fcfe4b4585e64ce63d96"
        
        // 当点击了取消后授权后都会加载授权回调地址，所以判断如果是授权回调地址就表示点击的是取消或授权
        // 不是授权回调地址，让他加载
        if !urlString.hasPrefix(redirect_uri) {
            return true
        } else {
            // 加载的授权回调地址，说明点击的是 取消 或 授权
            // 获取参数
            // query:get请求 ？后面的参数
            let query = request.URL?.query
            
            // 判断query是否以 code= 开头
            let codeString = "code="
            
            if query!.hasPrefix(codeString) {
                // 点击的是授权
                // "code=510e071daf99fcfe4b4585e64ce63d96"
                // 截取query里面的code
                let nsQuery = query! as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)

                print("code:\(code)")
                
            QBUserAccountViewModel.sharedInstance.loadAccessToken(code, completion: { (error) -> () in
                
                // 判断是否有错
                if error != nil {
                    print("error:\(error)")
                    
                    SVProgressHUD.showErrorWithStatus("获取AccessToken失败")
                
                    // 延迟1秒
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    
                        self.close()
                    })
                    return
                }
                
                print("没有错误关闭控制器")
                self.close()
                
                // 切换控制器
//                let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
//                
//                appDelegate?.window?.rootViewController = QBWelcomeViewController()
                AppDelegate.outSwitchRootViewController(QBWelcomeViewController())
                
            })
                
            } else {
                // 点击的是取消
                // 关闭界面
                close()
            }
            return false
        }
    }
    

}
